<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace slinks\core\DependencyInjection\Compiler;

use slinks\core\DependencyInjection\ContainerBuilder;

/**
 * Merges extension configs into the container builder
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
class MergeExtensionConfigurationPass implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
    	
    	$parameters = $container->getParameterBag()->all();
        $definitions = $container->getDefinitions();
        $aliases = $container->getAliases();

        // it is possible that extensions configure extensions 
        $extensions = $container->getExtensionConfigs();
        $container->setExtensionConfigs(array());
        
        while(count($extensions)>0){
	        foreach ($extensions as $name => $configs) {
	            list($namespace, $tag) = explode(':', $name);
	
	            $extension = $container->getExtension($namespace);
	
	            $tmpContainer = new ContainerBuilder($container->getParameterBag());
	            $tmpContainer->addDefinitions($container->getDefinitions());
	            $tmpContainer->addAliases($container->getAliases());
	            
	            $tmpContainer->addObjectResource($extension);
	           
	            foreach ($configs as $config) {
	                $extension->load($tag, $config, $tmpContainer);
	            }
	
	            $container->merge($tmpContainer);
	        }
	        $extensions = $container->getExtensionConfigs();
	        $container->setExtensionConfigs(array());
        }
        
        $container->addDefinitions($definitions);
        $container->addAliases($aliases);
        $container->getParameterBag()->add($parameters);
    
    }
}
